package net.piggy.config.security.rule;

import net.piggy.model.agg.SecurityUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import java.util.Collection;

@Component
public class VerifyRule {

    public final boolean hasRole(String... roles) {
        SecurityUser details = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getDetails();
        Collection<SimpleGrantedAuthority> collection = details.getRoles();
        return has(collection, roles);
    }

    public final boolean hasAuthority(String... authorities) {
        SecurityUser details = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getDetails();
        Collection<SimpleGrantedAuthority> collection = details.getAuthorities();
        return has(collection, authorities);
    }

    private boolean has(Collection<SimpleGrantedAuthority> collection, String... params){
        for(String param: params){
            if(collection.contains(new SimpleGrantedAuthority(param))){
                return true;
            }
        }
        return false;
    }
}
